import { IGameOverCheck } from "@/controler/GameOverCheck/IGameOverCheck";
import { IGameState } from "@/model/IGameState";
import { IGameOver } from "@/model/IGameOver";

export class TicTacTocCheck implements IGameOverCheck {
  Check(state: IGameState): IGameOver {
    const winner = TicTacTocCheck.calculateWinner(state.Squares);
    console.log(winner);

    let isOver: boolean;
    if (winner) {
      isOver = true;
    } else {
      isOver = TicTacTocCheck.calculateOver(state.Squares);
    }

    return {
      IsOver: isOver,
      Winner: winner ? winner : ""
    };
  }

  private static calculateWinner(squares: string[]): string | null {
    const lines = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6]
    ];
    for (let i = 0; i < lines.length; i++) {
      const [a, b, c] = lines[i];
      if (
        squares[a] &&
        squares[a] === squares[b] &&
        squares[a] === squares[c]
      ) {
        return squares[a];
      }
    }
    return null;
  }

  private static calculateOver(Squares: string[]): boolean {
    return Squares.indexOf("") === -1;
  }
}
